package com.tjhzzx.ibmsSupervisor.history;

import com.tjhzzx.ibmsSupervisor.history.entities.HistoryDataItem;
import com.tjhzzx.ibmsSupervisor.history.entities.HistoryDataMessage;
import com.tjhzzx.ibmsSupervisor.history.entities.HistoryDataUnit;
import com.tjhzzx.ibmsSupervisor.util.TimeUtil;
import org.apache.commons.lang3.StringUtils;

import javax.baja.collection.BITable;
import javax.baja.history.*;
import javax.baja.history.db.BHistoryDatabase;
import javax.baja.sys.BAbsTime;
import javax.baja.sys.Cursor;
import javax.baja.sys.Sys;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class HistoryManager {
//    private static final Logger LOGGER = Logger.getLogger(HistoryManager.class.getName());
    private static int MAX_COUNT = 90000;

    public static HistoryDataMessage searchHistoryData(HistoryDataMessage request) {
        HistoryDataMessage result = new HistoryDataMessage();

        result.responseCode = HistoryDataMessage.ERROR;
        if ((request.items == null) || (request.items.size() == 0)) {
            return result;
        }
        int totalCount = 0;
        List<HistoryDataItem> responseItems = new ArrayList<>();
        for(HistoryDataItem item : request.items) {
            HistoryDataItem responseItem = new HistoryDataItem();
            responseItem.name = item.name;
            BHistoryDatabase db = ((BHistoryService) Sys.getService(BHistoryService.TYPE)).getDatabase();
            if(null == db) {
                return result;
            }
            HistorySpaceConnection conn = db.getConnection(null);
            if(null == conn) {
                return result;
            }
            BIHistory history = conn.getHistory(BHistoryId.make(item.ord));
            if(null == history) {
                return result;
            }
            BAbsTime startTime;
            if (StringUtils.isBlank(request.startTime)) {
                startTime = conn.getFirstTimestamp(history);
            } else {
                startTime = TimeUtil.makeEqualAbsTime(request.startTime);
            }
            BAbsTime endTime;
            if (StringUtils.isBlank(request.endTime)) {
                endTime = BAbsTime.now();
            } else {
                endTime = TimeUtil.makeEqualAbsTime(request.endTime);
            }
            BITable<BHistoryRecord> table = conn.timeQuery(history, startTime, endTime);
            if (table != null) {
                List<HistoryDataUnit> historyDataUnits = new LinkedList<>();
                Cursor<BHistoryRecord> cursor = table.cursor();
                while (cursor.next()) {
                    BHistoryRecord rec = cursor.get();
                    BAbsTime historyTime = rec.getTimestamp();
                    String historyValue = "";
                    if ((rec instanceof BNumericTrendRecord)) {
                        historyValue = toMathRoundString(((BNumericTrendRecord) rec).getValue());
                        if (!checkNumberLegal(historyValue)) {
                            historyValue = "null";
                        }
                    } else if ((rec instanceof BEnumTrendRecord)) {
                        historyValue = ((BEnumTrendRecord) rec).getValue().getTag();
                    } else if ((rec instanceof BStringTrendRecord)) {
                        historyValue = ((BStringTrendRecord) rec).getValue();
                    } else if ((rec instanceof BBooleanTrendRecord)) {
                        historyValue = ((BBooleanTrendRecord) rec).getValue() ? "1" : "0";
                    }
                    HistoryDataUnit unit = new HistoryDataUnit();
                    unit.time = TimeUtil.getFormatTimeString(historyTime, "YY-MM-DD hh:mm:ss");
                    unit.value = historyValue;
                    historyDataUnits.add(unit);
                    totalCount++;
                }
                responseItem.units = historyDataUnits;
            }
            responseItems.add(responseItem);
        }
        result.items = responseItems;
        if (totalCount > MAX_COUNT) {
            result.items = null;
            result.responseCode = HistoryDataMessage.DATA_OVERFLOW;
            return result;
        }
        request.responseCode = HistoryDataMessage.OK;
        return result;
    }

//    public static List<HistoryTreeParam> getHistoryTreeItems(BTreeMenuItem menu) {
//        List<HistoryTreeParam> params = new ArrayList<>();
//        if (null == menu) {
//            return params;
//        }
//        return getHistoryTreeItems(menu.getHistorySearchParamRoot());
//    }

//    public static HistoryTreeParam[] getHistoryTreeItems(BBaseServlet servlet) {
//        HistoryTreeParam[] items = null;
//        if (null == servlet) {
//            return items;
//        }
//        return getHistoryTreeItems(servlet.getHistoryRoot());
//    }

//    private static List<HistoryTreeParam> getHistoryTreeItems(BComponent historySearchParam) {
//        List<HistoryTreeParam> items;
//        BComponent[] children = historySearchParam.getChildComponents();
//        if ((null == children) || (children.length == 0)) {
//            return null;
//        }
//        items = new ArrayList<>();
//        for (int i = 0; i < children.length; i++) {
//            HistoryTreeParam item = new HistoryTreeParam();
//            BComponent child = children[i];
//            if ((child instanceof BSearchParamGroup)) {
//                BSearchParamGroup group = (BSearchParamGroup) child;
//                item.setName(SlotPath.unescape(group.getName()));
//                item.setOrd("");
//                item.setItems(getHistoryTreeItems(group));
//            } else if ((child instanceof BSearchParamItem)) {
//                BSearchParamItem paramItem = (BSearchParamItem) child;
//                item.setName(SlotPath.unescape(paramItem.getName()));
//                BHistory fxh = null;
//                try {
//                    fxh = (BHistory) paramItem.getHistoryOrd().resolve().get();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    continue;
//                }
//                item.setOrd(fxh.getId().toString());
//                item.setItems(null);
//            }
//            items.add(item);
//        }
//        return items;
//    }

    public static String toMathRoundString(double d) {
        return String.valueOf(Math.round(d * 100.0D) / 100.0D);
    }

    public static boolean checkNumberLegal(String data) {
        try {
            Double.parseDouble(data);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
